if(typeof window === "undefined"){
    global.window = {}
}

const fs = require("fs");
const path = require("path");
const express = require("express");
const {renderToString} = require("react-dom/server.js");
const SSR = require("../dist/search-server.js");
const data = require("./data.json");

const template = fs.readFileSync(path.join(__dirname,'../dist/search.html'),"utf-8")

const server = (port) => {
    const app = express();

    app.use(express.static("dist"));

    app.get("/search",(req,res) => {
        res.status(200).send(renderMarkUp1(renderToString(SSR)));
    });

    app.listen(port,()=>{
        console.log("server is on running ")
    })
};

server(process.env.PORT || 3000);

const renderMarkUp =  (str) =>{
    return `<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        ${str}
    </body>
    </html>`
};

const renderMarkUp1 =  (str) =>{
    let dataJson = JSON.stringify(data);
    let replaceStr = `<script>window.__initial_data=${dataJson}</script>`
    return template.replace("<!--HTML_REPLACEHOLDER-->",str)
        .replace("<!--DATA_REPLACEHOLDER-->",replaceStr);
};